﻿using System;
using System.ComponentModel;
using System.Drawing;
using System.IO;
using System.Windows.Forms;
using WF = System.Windows.Forms;
using AxWMPLib;

namespace UpwardsTimeClock.Prototype
{
    public class VideoControl : VisualControlBase<Video>
    {
        private AxWindowsMediaPlayer _mediaPlayer;
        private WF.Timer _fullScreenTimer;
        private bool _gotVideo;

        public VideoControl(Video config): base(config)
        {
            _mediaPlayer = new AxWindowsMediaPlayer();
        }

        protected override Control CreateVisualControl()
        {
            return _mediaPlayer;
        }

        public override void Initialize(Control.ControlCollection controls)
        {
            string videoPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Videos");
            string videoFile = Program.BuildFilePath(videoPath, Config.VideoFile);

            if (videoFile != null)
            {
                ((ISupportInitialize)_mediaPlayer).BeginInit();
                _mediaPlayer.Enabled = true;

                _mediaPlayer.Name = Config.Key;
                _mediaPlayer.Location = new Point(0, 0);

                base.Initialize(controls);

                _mediaPlayer.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Bottom | AnchorStyles.Right;
                ((ISupportInitialize)_mediaPlayer).EndInit();

                _gotVideo = true;
                _mediaPlayer.uiMode = "none";
                _mediaPlayer.Ctlenabled = true;
                _mediaPlayer.URL = videoFile;
                _mediaPlayer.Ctlcontrols.pause();
            }
            else
            {
                base.Initialize(controls);
            }

        }

        void FullScreenTimer_Tick(object sender, EventArgs e)
        {
            try
            {
                _mediaPlayer.fullScreen = true;
                _fullScreenTimer.Dispose();
            }
            catch { }
        }

        public override void Start()
        {
            base.Start();
            if (_gotVideo)
            {
                _mediaPlayer.Ctlcontrols.play();
                if (Config.FullScreen)
                {
                    _fullScreenTimer = new System.Windows.Forms.Timer();
                    _fullScreenTimer.Interval = 500;
                    _fullScreenTimer.Tick += FullScreenTimer_Tick;
                    _fullScreenTimer.Start();
                }
            }
        }

        public override void Stop()
        {
            _mediaPlayer.Ctlcontrols.stop();
            base.Stop();
        }
    }
}
